<?php

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\JWT;
use GenTux\Jwt\GetsJwtToken;

class User
{

    use GetsJwtToken;

    public function __construct()
    {
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->userId = 0;
        $token           = $this->getToken();
        if ($token) {
            $arr     = explode('.', $token);
            if(count($arr)<=1){
                return $next($request);
            }
            $payLoad = json_decode(JWT::urlsafeB64Decode($arr[1]), true);
            //20240125加此代码，有可能payload里面的exp已过期，直接调用$this->jwtPayload()会报token已过期，详情查看源码，所以换种方式拿payload里面的值,因为此处需要拿用户id和UserAuth中间件做区分（即有些接口需要登录和不登录的区别）
            //$payLoad         = $this->jwtPayload();
            $request->userId = $payLoad['uid'];
        }
        return $next($request);

    }


}
